﻿Wheels.TripPlannerResults = new Ext.form.ItineraryList({ listeners: { single: true }, style: 'background-color: white' });

// get Date javascript object from date "json date string"
function getDate(value) {
    value = value.replace('/Date(', '');
    value = value.replace(')/', '');
    return new Date(parseInt(value));
}

// get date sa string in format: 08:37 AM
function getTimeFromJSONString(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var am = "PM";
    if (hours > 12) {
        am = "AM";
        hours = hours - 12;
    }
    if (hours.toString().length == 1) {
        hours = "0" + hours;
    }
    if (minutes.toString().length == 1) {
        minutes = "0" + minutes;
    }
    return hours + ":" + minutes + " " + am;
}

function getDateFromJSONString(date) {
    var days = date.getDay();
    var months = date.getMonth();
    var years = date.getYear() + 1900;
    if (days < 10) {
        days = "0" + days;
    }
    if (months < 10) {
        months = "0" + months;
    }
    return days + "/" + months + "/" + years;
}

// get time span as string in format: 01h:12m
// input: two dates as "json date string"
function getDurationByDates(date1Ticks, date2Ticks) {

    var date1 = getDate(date1Ticks);
    var date2 = getDate(date2Ticks);

    var duration = (date2.getTime() - date1.getTime()) / 1000;
    return getDurationBySeconds(duration);
}

// get time span as string in format: 01h:12m
// input count of the seconds
function getDurationBySeconds(duration) {
    var hours = parseInt(duration / 3600);
    var minutes = parseInt((duration - (hours * 3600)) / 60);

    if (hours.toString().length == 1) {
        hours = "0" + hours;
    }
    if (minutes.toString().length == 1) {
        minutes = "0" + minutes;
    }
    return hours.toString() + "h:" + minutes.toString() + "m";
}

function getResults() {
    var list = Wheels.TripPlannerResults;

    this.isLoaded = false;
    Ext.getBody().unmask();
    Ext.getBody().mask(false, '<div class="demos-loading">Loading&hellip;</div>');

    var lat1, lon1, lat2, lon2;

    lat1 = Trip.Departure.Lat;
    lon1 = Trip.Departure.Lng;
    lat2 = Trip.Arrival.Lat;
    lon2 = Trip.Arrival.Lng;

    var filter = '';
    var orderby = '&$orderby='
    var trip = TripPlan.data;

    switch (trip.use) {
        case "bus":
            filter += "&$filter=not%20substringof('Metro',TravelTypes)"
            break;
        case "rail":
            filter += "&$filter=not%20substringof('Bus',TravelTypes)"
            break;
    }

    switch (trip.minimize) {
        case "transfers":
            orderby += "TransferCount asc";
            break;
        /*
        case "time":
        orderby = "???";
        case "walking":
        orderby = "???";
        */ 
    }

    $.getJSON("http://transit.cloudapp.net/DevTransitODataService.svc/CalculateItineraryByPoints?lat1="
     + lat1 + "&lon1=" + lon1 + "&lat2=" + lat2 + "&lon2=" + lon2 + "&$format=json&$callback=?&$expand=Legs&$top=5" + filter + orderby, function (result) {
         if (result != null) {
             $.each(result.d.results, function () {
                 this.Duration = getDurationByDates(this.StartTime, this.EndTime);
                 this.StartTime = getTimeFromJSONString(getDate(this.StartTime));
                 this.EndTime = getTimeFromJSONString(getDate(this.EndTime));

                 var walkDistance = 0;
                 var allDistance = 0;
                 var legsHtml = "";

                 for (var i = 0; i < this.Legs.results.length - 1; i++) {
                     var leg = this.Legs.results[i];

                     pointType = "middle";
                     if (i == 0) { pointType = "start" };
                     if (i == this.Legs.results.length - 2) { pointType = "finish" };

                     if (leg.TransportType.toString().toLowerCase() == "walk") {
                         walkDistance += leg.Length;
                     }
                     allDistance += leg.Length;
                     legsHtml += buildLegHtml(leg, pointType);
                 }

                 this.LegsHtml = legsHtml;
                 this.WalkDistance = walkDistance;
                 this.Distance = allDistance;
                 this.Transfers = this.Legs.results.length;
             });

             var store = new Ext.data.Store({
                 model: 'Itinerary',
                 data: result.d.results
             });
             
             list.setStore(store);
             list.refresh();

             Ext.getBody().unmask();
             this.isLoaded = true;
         }
     });
};

function buildLegHtml(leg, pointType) {
    return '<li class="' + leg.TransportType.toLowerCase() + '"><div class="' + pointType + '">' + coalesce(leg.RouteId, '&nbsp;') + '</div></li>';
}
